var service_user = require("../../service/user.js");
var service_common = require("../../service/common.js");
var user_info_temp = {}
Page({
  data: {
    userInfo: {},
    photoString: "",
    addcss: "",
    photo_css: "display:none",
    phone: "",
    save_button: "",
    more_info_temp: "",
    typeArray: getApp().globalData.typeArray,
    typeIndex: 0,
    isPhoneNumber: false,
    phoneNumber: "",
    checked:true,
    bdOffon:false, 
    phone_mob:'',
    Code_:0,
    time:60,
    bd_value:''
  },
  /**
   * 获取用户手机号码
   */
  getPhoneNumber: function (e) {
    
    var that = this;
  
    service_user.getMobileNumber(e.detail.encryptedData, e.detail.iv, function (res) {
      if (res.data.code == 0) {
        user_info_temp["mobile"] = res.data.data;
        that.setData({
          userInfo: user_info_temp,
          phone_mob: res.data.data
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '获取手机号失败',
          showCancel: false,
        })
      }
    })
  },
  /**
   * 页面初始化
   */
  onLoad: function () {
    var that = this
 
    wx.showLoading({
      title: "加载数据中",
      mask: true
    })
    var typeArray = [];
    typeArray[0] = "请选择";
    for (var i = 1; i < getApp().globalData.typeArray.length; i++) {
      typeArray[i] = getApp().globalData.typeArray[i];
    }
    this.setData({
      typeArray: typeArray
    })
    //调用应用实例的方法获取全局数据
    service_user.login2(function (userInfo) {
      //更新数据
      console.log(userInfo)
      that.setData({
        userInfo: userInfo,
        phone_mob: userInfo.mobile
      })
      that.getUserTags()
      user_info_temp = userInfo
      for (var i = 0; i < that.data.typeArray.length; i++) {
        console.log(that.data.userInfo.type)
        if (that.data.userInfo.type == that.data.typeArray[i]) {
          that.setData({
            typeIndex: i
          })
        }
      }
      //设置标题
      wx.setNavigationBarTitle({
        title: userInfo.nickname + " 的名片"
      })
      that.getUserImage()
      wx.hideLoading();
    })
  },
  // 获取自己的标签
  getUserTags:function(){

  },
  // 获取验证码
  getYzm:function(){
      this.setData({
        bdOffon:true
      })
      var t =setInterval(()=>{
        if (this.data.time<=0){
          this.setData({
            time:60
          })
          clearInterval(t)
          return
        }
        this.data.time-=1
        this.setData({
          time: this.data.time
        })
        
      },1000)
      service_common.fetchData(
        service_common.getUrl("user.sendCode"),
        {
          phone: this.data.phone_mob,
          type: 5
        },
        (res)=>{
         
        },
        "GET"
      )
  },
  getCode:function(e){
    // e.detail.value
    this.setData({
      Code_: e.detail.value
    })
    
  },
  bdPhone:function(){
 
    if (this.data.userInfo.is_mobile_verified == 0) {//未绑定
      service_common.fetchData(
        service_common.getUrl("user.bindPhone"),
        {
          openid: this.data.userInfo.openid,
          phone: this.data.phone_mob,
          code: this.data.Code_,
          unionid: getApp().globalData.userInfo.unionid
        },
        (res) => {
     
          this.setData({
            bdOffon:false,
            bd_value:''
          })
          this.onLoad()
          wx.showToast({
            title: '绑定成功',
          })
        },
        "GET"
      )
    }else{
      console.log("=-=-=-=-=-")
      service_common.fetchData(//解绑手机号
        service_common.getUrl("user.unbindPhone"),
        {
          openid: this.data.userInfo.openid,
          phone: this.data.phone_mob,
          code: this.data.Code_,
          unionid: getApp().globalData.userInfo.unionid
        },
        (res) => {
          this.setData({
            bdOffon: false,
            bd_value:''
          })
          this.onLoad()
          wx.showToast({
            title: '解绑成功',
          })
        },
        "GET"
      )
    }
  },
  /**
   * 分类下拉列表
   */
  bindPickerChange: function (e) {
    user_info_temp["type"] = this.data.typeArray[e.detail.value];
    this.setData({
      typeIndex: e.detail.value
    })
  },
  /**
   * 表单提交
   */
  save: function (e) {
    var that = this;
    var pattern = /^[\u4e00-\u9fa5]{0,}$/
    if (pattern.test(user_info_temp["email"]).length>0){
      wx.showToast({
        title: '微信不能为中文',
        image: '../../image/wrong.png',
        duration: 500
      })
    }else if (that.data.typeIndex == 0) {
      wx.showToast({
        title: '请选择分类',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else if (user_info_temp["company"].replace('/(^/s *)| (/s*$)/g', "") == "") {
      wx.showToast({
        title: '请填写公司名',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else if (user_info_temp["job"].replace('/(^/s *)| (/s*$)/g', "") == "") {
      wx.showToast({
        title: '请填写职务',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else if (user_info_temp["email"].replace('/(^/s *)| (/s*$)/g', "") == "") {
      wx.showToast({
        title: '请填写微信号',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else if (user_info_temp["wechat"].replace('/(^/s *)| (/s*$)/g', "") == "") {
      wx.showToast({
        title: '请填写邮箱',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else if (user_info_temp["mobile"].replace('/(^/s *)| (/s*$)/g', "") == "") {
      wx.showToast({
        title: '请填写手机号',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else if (user_info_temp["mobile"].length > 15 || isNaN(user_info_temp["mobile"])) {
      wx.showToast({
        title: '手机号不存在',
        image: '../../image/wrong.png',
        duration: 500
      })
    } else {
      
      if (this.data.checked==true){
        wx.showLoading({
          title: '保存中',
          mask: true
        })
        service_user.saveUserInfo(user_info_temp, that.saveCallBack);
      }else{
        wx.showModal({
          title: '提示',
          content: '请勾选用户协议',
        })
      }
      
    }
  },
  /**
   * 保存呢称
   */
  saveName: function (e) {
    if ((e.detail.value).length <= 10) {
      this.setData({
        name: "",
        save_button: ""
      })
    } else {
      this.setData({
        name: "名字过长",
        save_button: true
      })
    }
    user_info_temp["name"] = e.detail.value;
  },

  /**
   * 保存姓名
   */
  saveNickName: function (e) {
    if ((e.detail.value).length <= 10) {
      this.setData({
        name: "",
        save_button: ""
      })
    } else {
      this.setData({
        name: "名字过长",
        save_button: true
      })
    }
    user_info_temp["nickname"] = e.detail.value;
  },
  /**
  * 保存手机号
  */
  savePhone: function (e) {
    this.setData({
      phone_mob: e.detail.value
    })
    user_info_temp["mobile"] = e.detail.value;
  },
  /**
  * 保存公司
  */
  saveCompany: function (e) {
    user_info_temp["company"] = e.detail.value;
  },
  /**
  * 保存职位
  */
  saveJob: function (e) {
    user_info_temp["job"] = e.detail.value;
  },
  /**
  * 保存微信
  */
  saveWechat: function (e) {
    user_info_temp["email"] = e.detail.value;
  },
  /**
   * 保存邮箱
   */
  saveEmail: function (e) {
    user_info_temp["wechat"] = e.detail.value;
  },
  /**
   * 保存用户简介
  */
  saveMoreInfo: function (e) {
    user_info_temp["more_info"] = e.detail.value;
  },
  /**
   * 保存信息回调
   */
  saveCallBack: function (res) {
    if (res.data.code == 0) {
      wx.hideLoading();
      console.log(res)
      // if (!res.data.location) {
      //   console.log(res.data)
      //   wx.showModal({
      //     title: '提示',
      //     content: '请先允许获取您的地理位置',
      //     showCancel: false,
      //     confirmText: "去设置",
      //     success: res => {
      //       if (res.confirm) {
      //         wx.openSetting({
      //           success: res => {
      //             if (!res.authSetting["scope.userLocation"]) {
      //               wx.showModal({
      //                 title: '提示',
      //                 content: '授权失败',
      //                 showCancel: false,
      //                 success: res => {
      //                   console.log(res)
      //                   wx.switchTab({
      //                     url: '../my/my',
      //                   })
      //                 }
      //               })
      //             } else {
      //               wx.showModal({
      //                 title: '提示',
      //                 content: '授权成功',
      //                 showCancel: false,
      //                 success: res => {
      //                   wx.getLocation({
      //                     success: function (res) {
      //                       wx.request({
      //                         url: getApp().globalData.API_Base_URL + "/uri/user/saveUserLocation",
      //                         data: {
      //                           openid: getApp().globalData.openid,
      //                           latitude: res.latitude,
      //                           longitude: res.longitude,
      //                           version:getApp().globalData.version
      //                         },
      //                         complete: res => {
      //                           console.log("fuck",res);
      //                           wx.switchTab({
      //                             url: '../my/my',
      //                           })
      //                         }
      //                       })
      //                     },
      //                   })
      //                 }
      //               })
      //             }
      //           }
      //         })
      //       }
      //     }
      //   })
      // } else {
       
      // }
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
  },
  /**
   * 上传图片
   */
  uploadImage: function () {
    var that = this
    var temp = [];
    wx.chooseImage({
      count: (6 - that.data.image_array.length),
      sizeType: ['compressed'],
      success: function (res) {
        temp = res.tempFilePaths;
      },
      complete: res => {
        for (var i = 0; i < temp.length; i++) {
          console.log("fuck you")
          var filePath = temp[i];
          wx.uploadFile({
            url: getApp().globalData.API_Base_URL + "/uri/user/uploadImage",
            filePath: filePath,
            name: "file",
            formData: {
              'version': getApp().globalData.version,
              'openid': getApp().globalData.openid,
              'user_id': getApp().globalData.userInfo["id"],
              "token": wx.getStorageSync('token__'),
              "token_key": wx.getStorageSync('token_key')
            },
            success: function (res) {
              wx.hideLoading()
              if (res.statusCode == 200) {
                that.getUserImage()
              } else {
                wx.showModal({
                  title: '提示',
                  content: '上传失败，请重试',
                  showCancel: false,
                  success: res => {

                  }
                })
              }
            }
          })
        }
      }
    })

  },
  /**
   * 获取用户图片
   */
  getUserImage: function () {
    var that = this;
    service_user.getUserImage(getApp().globalData.openid, function (res) {
      that.setData({
        image_array: res.data.data,
      })
      if (res.data.data.length > 0) {
        that.setData({
          photo_css: ""
        })
      } else {
        that.setData({
          photo_css: "display:none;"
        })
      }
      if (res.data.data.length < 6) {
        that.setData({
          addcss: ""
        })
      } else {
        that.setData({
          addcss: "display:none;"
        })
      }
    });
  },
  /**
   * 图片预览
   */
  showPhoto: function (e) {
    var id = e.currentTarget.id;
    var array = [];
    for (var i = 0; i < this.data.image_array.length; i++) {
      array[i] = this.data.image_array[i].b;
    }
    wx.previewImage({
      current: array[id],
      urls: array
    })
  },
  /**
   * 删除图片
   */
  deleteImage: function (e) {
    var id = e.currentTarget.id
    var that = this;
    service_user.deleteImage(id, function (res) {
      if (res.data.code == 0) {
        wx.showToast({
          title: '删除成功',
          mask: true
        })
        that.getUserImage()
      } else {
        wx.showToast({
          title: '删除失败',
          mask: true
        })
      }
    })
  },
  checkboxChange:function(e){
    if (e.detail.value[0] == '1'){
        this.setData({
          checked:true
        })
    }else{
      this.setData({
        checked: false
      })
    }
  },
  Xieyi:function(){
    wx.navigateTo({
      url: '/pages/Xy/Xy',
    })
  },
  /**
   * 上传头像
   */
  updateHeadImg: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      success: function (res) {
        wx.showLoading({
          title: '保存中',
          mask: true
        })
        var filePath = res.tempFilePaths[0];
        wx.uploadFile({
          url: getApp().globalData.API_Base_URL + "/uri/user/uploadHeadImage",
          filePath: filePath,
          name: "file",
          header: { "Content-Type": "multipart/form-data" },
          formData: {
            'version': getApp().globalData.version,
            'openid': getApp().globalData.openid,
            'user_id': getApp().globalData.userInfo["id"],
          },
          success: function (res) {
            wx.hideLoading();
            if (res.statusCode == 200) {
              getApp().globalData.userInfo.src = filePath;
              user_info_temp["src"] = filePath;
              that.setData({
                userInfo: user_info_temp
              })
            } else {
              wx.showModal({
                title: '提示',
                content: '上传失败，请重试',
                showCancel: false,
                success: res => {
                  //that.getUserImage()
                }
              })
            }
          }
        })
      }
    })
  },
})
